﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Xml.Linq;
using APIBetaSeries.Models.Member;
using APIBetaSeries.Tools;

namespace APIBetaSeries.Managers
{
    public class MemberManager
    {
        private static volatile MemberManager _instance;
        private static Object _syncRoot = new Object();

        private MemberManager()
        {
        }

        public static MemberManager Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncRoot)
                    {
                        if (_instance == null)
                            _instance = new MemberManager();
                    }
                }
                return _instance;
            }
        }

        public Member Connect(String login, String password, Boolean isHashed)
        {
            const string url = "members/auth.xml";
            Dictionary<String, String> values = new Dictionary<String, String>
                {
                    {"login",login},
                    {"password", isHashed ? password : MD5Hasher.Hash(password)}
                };
            XDocument xDocument = Requester.Instance.SendMessage(url, values);
            Member response = new Member(xDocument);
            return response;
        }

        public Member Disconnect(String token)
        {
            const string url = "members/destroy.xml";
            Dictionary<String, String> values = new Dictionary<string, string>
                {
                    {"token", token}
                };
            XDocument xDocument = Requester.Instance.SendMessage(url, values);
            return new Member(xDocument);
        }

        public Member IsActive(String token)
        {
            const string url = "members/is_active.xml";
            Dictionary<String, String> values = new Dictionary<string, string>
                {
                    {"token", token}
                };
            return new Member(Requester.Instance.SendMessage(url, values));
        }

        public Member GetInfos(String login, Boolean? noData, String timeStamp)
        {
            String url = "members/infos/" + login + ".xml";
            Dictionary<String, String> values = new Dictionary<string, string>();
            if (noData.HasValue)
                values.Add("nodata", Convert.ToInt32(noData.Value).ToString());
            if (!String.IsNullOrEmpty(timeStamp))
                values.Add("since", timeStamp);
            return new Member(Requester.Instance.SendMessage(url, values));
        }
    }
}
